"""
语音控制器 - 使用百度语音识别
"""
import pyttsx3
import threading
import queue
import time
from baidu_asr import BaiduASR
from config import VOICE_FEEDBACK, VOICE_RATE, VOICE_VOLUME

class VoiceController:
    def __init__(self, llm_client):
        self.llm_client = llm_client
        self.baidu_asr = BaiduASR()
        
        # 初始化语音合成
        self.tts_engine = pyttsx3.init() if VOICE_FEEDBACK else None
        if self.tts_engine:
            self.tts_engine.setProperty('rate', VOICE_RATE)
            self.tts_engine.setProperty('volume', VOICE_VOLUME)
        
        # 语音命令队列
        self.command_queue = queue.Queue()
        self.listening = False
    
    def speak(self, text):
        """语音反馈"""
        if self.tts_engine and VOICE_FEEDBACK:
            try:
                print(f"语音反馈: {text}")
                self.tts_engine.say(text)
                self.tts_engine.runAndWait()
            except:
                print(f"语音反馈失败: {text}")
        else:
            print(f"系统: {text}")
    
    def listen_for_trigger(self):
        """监听键盘输入触发语音识别"""
        self.listening = True
        print("🎤 语音控制系统已启动（百度语音识别）")
        print("💡 输入 'a' 开始5秒语音识别")
        print("💡 输入 'q' 退出系统")
        
        while self.listening:
            try:
                user_input = input("请输入指令 (a=语音识别, q=退出): ").strip().lower()
                
                if user_input == 'a':
                    print("🎤 开始5秒语音识别...")
                    command = self.record_and_process_voice()
                    if command:
                        self.command_queue.put(command)
                        print(f"📥 命令已加入队列: {command}")
                    
                elif user_input == 'q':
                    print("🛑 退出语音控制")
                    self.listening = False
                    break
                    
                else:
                    print("❌ 无效输入，请输入 'a' 或 'q'")
                    
            except KeyboardInterrupt:
                print("\n🛑 收到退出信号")
                self.listening = False
                break
            except Exception as e:
                print(f"❌ 输入处理错误: {e}")
                continue
        
        print("🛑 语音监听已停止")
    
    def record_and_process_voice(self):
        """使用百度语音识别录制并处理语音，支持复合指令"""
        try:
            # 使用百度ASR录制音频
            audio_file = self.baidu_asr.record_audio(duration=5)
            if not audio_file:
                self.speak("录音失败")
                return None
            
            # 识别语音
            voice_text = self.baidu_asr.recognize_audio_file(audio_file)
            
            if voice_text:
                print(f"✅ 百度识别到语音: '{voice_text}'")
                
                # 使用LLM解析命令（支持复合指令）
                print(f"🤖 发送到LLM解析: {voice_text}")
                commands = self.llm_client.parse_voice_command(voice_text)
                
                if isinstance(commands, list):
                    if len(commands) > 1:
                        print(f"🎯 LLM解析出复合指令: {voice_text} -> {commands}")
                        valid_commands = [cmd for cmd in commands if cmd != "unknown"]
                        if valid_commands:
                            if len(valid_commands) > 1:
                                self.speak(f"收到复合指令，共{len(valid_commands)}条")
                            else:
                                self.speak(f"收到指令: {valid_commands[0]}")
                            return valid_commands
                        else:
                            print("❌ 所有指令都无法解析")
                            self.speak("抱歉，无法识别该指令")
                            return None
                    else:
                        command = commands[0] if commands else "unknown"
                        print(f"🎯 LLM解析结果: {voice_text} -> {command}")
                        if command and command != "unknown":
                            self.speak(f"收到指令: {command}")
                            return [command]
                        else:
                            print("❌ 无法解析的指令")
                            self.speak("抱歉，无法识别该指令")
                            return None
                else:
                    # 兼容旧格式（单个字符串）
                    if commands and commands != "unknown":
                        self.speak(f"收到指令: {commands}")
                        return [commands]
                    else:
                        print("❌ 无法解析的指令")
                        self.speak("抱歉，无法识别该指令")
                        return None
            else:
                print("🔇 未识别到清晰语音，请重试")
                self.speak("未识别到清晰语音")
                return None
                
        except Exception as e:
            print(f"❌ 语音处理错误: {e}")
            self.speak("语音处理错误")
            return None
    
    def start_listening(self):
        """启动语音监听线程"""
        listen_thread = threading.Thread(target=self.listen_for_trigger)
        listen_thread.daemon = True
        listen_thread.start()
        return listen_thread
    
    def stop_listening(self):
        """停止语音监听"""
        self.listening = False
        self.speak("语音控制已停止")
    
    def get_command(self):
        """获取命令队列中的命令"""
        try:
            command = self.command_queue.get_nowait()
            print(f"📤 从队列取出命令: {command}")
            return command
        except queue.Empty:
            return None
    
    def test_voice_recognition(self):
        """测试百度语音识别"""
        try:
            print("🧪 测试百度语音识别（请说话3秒）...")
            return self.baidu_asr.test_recognition()
        except Exception as e:
            print(f"❌ 语音识别测试失败: {e}")
            return False